<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="父级" prop="pid">
        <el-cascader ref="cascaderSearchRef" v-model="queryParams.pid"
          @change="(val) => { cascaderClassChange(val, 'search') }" :options="areaOptions"
          :props="{ value: 'id', label: 'label', children: 'children', emitPath: false, checkStrictly: true }"
          placeholder="请选择父级" clearable filterable />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="地区编号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入地区编号" clearable @keyup.enter="handleQuery"
          oninput="value=value.replace(/[^\d]/g,'')" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['basic:area:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['basic:area:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['basic:area:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['basic:area:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border stripe v-loading="loading" :data="areaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" fixed="left" />
      <el-table-column label="父级" align="left" prop="parentName" :show-overflow-tooltip="true" />
      <el-table-column label="名称" align="left" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="地区编号" width="100" align="center" prop="code" />
      <el-table-column label="中心点经纬度" align="left">
        <template #default="scope">
          <span>{{ scope.row.longitude + ',' + scope.row.latitude }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['basic:area:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['basic:area:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改地区对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="areaRef" :model="form" :rules="rules" label-width="80px">
        <el-row gutter="10">
          <el-col>
            <el-form-item label="父级" prop="pid">
              <el-cascader ref="cascaderFormRef" v-model="form.pid"
                @change="(val) => { cascaderClassChange(val, 'form') }" :options="areaOptions"
                :props="{ value: 'id', label: 'label', children: 'children', emitPath: false, checkStrictly: true }"
                placeholder="请选择父级" filterable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区编号" prop="code">
              <el-input v-model="form.code" placeholder="请输入地区编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="auto" label="中心点经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入中心点经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="auto" label="中心点纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入中心点纬度" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status">
                <el-option v-for="dict in sys_data_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Area">
import { listArea, getArea, delArea, addArea, updateArea, areaTreeSelect } from "@/api/basic/area";
const { proxy } = getCurrentInstance();
const { sys_data_status } = proxy.useDict('sys_data_status');

const areaList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const areaOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pid: undefined,
    name: undefined,
    code: undefined,
    longitude: undefined,
    latitude: undefined,
    status: undefined,
  },
  rules: {
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "地区编号不能为空", trigger: "blur", pattern: /^[1-9]\d*$/ }

    ],
    pid: [
      { required: true, message: "父级不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询地区下拉树结构 */
function getAreaTree() {
  areaTreeSelect().then(response => {
    let init = [{
      id: 0,
      label: '顶级地区',
      parentId: 0
    }]
    let data = init.concat(response.data);
    //数据深拷贝
    let list = JSON.parse(JSON.stringify(data));
    //下拉选择用的数据只取两级的数据
    areaOptions.value = list.map(item => {
      if (item.children != undefined && Array.isArray(item.children)) {
        item.children.map(elem => {
          delete elem.children;
        })
        return item;
      }
      return item;
    });
  })
}

/** 三级联动选择地区改变面板隐藏问题. fix:因为设置checkStrictly的原因导致选择任意节点之后无法自动关闭面板 */
const cascaderSearchRef = ref();
const cascaderFormRef = ref();
function cascaderClassChange(val, args = 'search') {
  if (args == 'search') {
    console.log('搜索')
    //关闭搜索选择的面板
    cascaderSearchRef.value.togglePopperVisible(false)
  } else if (args == 'form') {
    console.log('新增或修改')
    //关闭新增或修改表单选择的面板
    cascaderFormRef.value.togglePopperVisible(false)
  }
}

/** 查询地区列表 */
function getList() {
  loading.value = true;
  listArea(queryParams.value).then(response => {
    areaList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {

  form.value = {
    id: null,
    pid: 0,
    name: null,
    code: null,
    longitude: null,
    latitude: null,
    status: '0',
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("areaRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加地区";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getArea(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改地区";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["areaRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateArea(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getAreaTree();
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addArea(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getAreaTree();
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除地区编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delArea(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basic/area/export', {
    ...queryParams.value
  }, `area_${new Date().getTime()}.xlsx`)
}

getAreaTree();

getList();
</script>
